package com.bbcare.nutritious.plat.service.imp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.entity.PtCourseBespeak;
import com.bbcare.nutritious.plat.entity.PtCourseInfo;
import com.bbcare.nutritious.plat.entity.PtWeight;
import com.bbcare.nutritious.plat.service.ICourseService;
import com.bbcare.nutritious.plat.service.IWeightService;
import com.bbcare.nutritious.plat.store.ibatis.ICourseDao;
import com.bbcare.nutritious.plat.store.ibatis.IWeightDao;

/**
 * 体重数据接口
 * @modify:
 *
 */
@Service
public class CourseService implements ICourseService {

	public static final Logger logger = Logger.getLogger(CourseService.class);

    @Autowired
    private IWeightDao weightDao;
    
    @Autowired
    private ICourseDao courseDao;
    
    /**
     * pc保存或修改课程信息
     */
    @Override
	public Map<String, Object> saveCourseInfo(PtCourseInfo courseInfo) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
    	courseInfo.setUpdateTime(nowTime);
    	if(courseInfo.getId()<=0){//id存在则保存
    		courseInfo.setCreateTime(nowTime);
    		courseDao.saveCourseInfo(courseInfo);
    	}else{//不存在则修改
    		courseDao.updateCourseInfo(courseInfo);
    	}
    	return rspMap;
	}
    /**
     * pc删除课程
     */
    @Override
	public Map<String, Object> delCourseInfo(PtCourseInfo courseInfo) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
    	courseInfo.setUpdateTime(nowTime);
    	courseDao.updateCourseInfo(courseInfo);
    	return rspMap;
	}
    /**
     * 分页查询课程
     */
    @Override
	public Map<String, Object> listCourseInfoForPage(PtCourseInfo courseInfo) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	List<PtCourseInfo> list = courseDao.listCourseInfo(courseInfo);
    	int totalCount =  courseDao.countCourseInfo(courseInfo);
    	
    	rspMap.put("rows", list);
     	rspMap.put("totalCount", totalCount);
 		return rspMap;
	}
    
   /**
    * 查询app用户课程预约首页接口实现
    * 1.查询近四天的课程
    * 2.查询当前年的所有课程
    */
    @Override
	public Map<String, Object> getCourseBespeakIndex(PtCourseInfo courseInfo) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	//判断该用户是否存在某租户下
    	String tenantId = weightDao.getUserTenantIdByUserId(courseInfo.getUserId());
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
    	courseInfo.setTenantId(tenantId);
    	courseInfo.setYearStr(DateTimeUtil.getYear()+"");//获取当前年份
    	//查询当前年的所有课程
    	List<PtCourseInfo> courseListThisYear = courseDao.listCourseInfo(courseInfo);
    	int total =  courseDao.countCourseInfo(courseInfo);
    	rspMap.put("courseListThisYear", courseListThisYear);
    	rspMap.put("courseListThisYearTotal", total);
    	//赋值当前日期	
    	courseInfo.setCourseDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));
    	//获取最近四天的所有课程
    	List<PtCourseInfo> courseListFourDay = courseDao.getCourseForFourDay(courseInfo);
    	//重新拼接四天的数据
    	int countForDay = courseDao.countCourseForFourDay(courseInfo);
    	List<Map<String,Object>> fourDayList = new ArrayList<Map<String,Object>>();
    	if(!CollectionUtils.isEmpty(courseListFourDay) && countForDay>0){
    		int i = 0;
    		for (int j = 0; j < countForDay; j++) {
    			List<PtCourseInfo> courseList = new ArrayList<PtCourseInfo>();
    			Map<String,Object> dayMap = Collections.synchronizedMap(new HashMap<String,Object>());
    			String date = courseListFourDay.get(i).getCourseDate();
    			for (; i < courseListFourDay.size(); i++) {
    				if(date.equals(courseListFourDay.get(i).getCourseDate())){
    					courseList.add(courseListFourDay.get(i));
    				}else{
    					dayMap.put("courseDate", date);
    					dayMap.put("courseList", courseList);
    					break;
    				}
    				if(i+1>=courseListFourDay.size()){
    					dayMap.put("courseDate", date);
    					dayMap.put("courseList", courseList);
    				}
        		}
    			fourDayList.add(dayMap);
			}
    		
    	}
    	rspMap.put("fourDayList", fourDayList);
		return rspMap;
	}
    /**
     * 通过id查询课程详细信息
     * @param courseInfo
     * @return
     * @throws Exception
     */
    @Override
	public Map<String, Object> getCourseInfoById(int id) throws Exception {
    	//创建线程安全的hashmap返回对象
    	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	PtCourseInfo courseInfo = courseDao.getCourseInfoById(id);
    	rspMap.put("fourDayList", courseInfo);
		return rspMap;
	}
    /**
     * 课程预约实现
     */
     @Override
 	public Map<String, Object> doCourseToBespeak(PtCourseBespeak courseBespeak) throws Exception {
     	//创建线程安全的hashmap返回对象
     	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
     	//判断该用户是否存在某租户下
     	String tenantId = weightDao.getUserTenantIdByUserId(courseBespeak.getUserId());
     	if(StringUtils.isEmpty(tenantId)){
     		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
     	}
     	courseBespeak.setBespeakState(1);//1：预约
     	//查询课程是否已经预约
     	int bespeakSum = courseDao.countCourseBespeak(courseBespeak);
     	//查询课程详细信息
     	PtCourseInfo course = courseDao.getCourseInfoById(courseBespeak.getCourseId());
     	if(course.getUpperLimit()<=course.getActualNum()){//判断预约人数是否已满
     		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"可预约人数已满");
     	}
     	if(DateTimeUtil.compareDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm), course.getEndTime(), DateTimeUtil.yyyy_MM_dd_HH_mm)==1){//判断预约人数是否已满
     		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"课程已结束");
     	}
     	if(!StringUtils.isEmpty(courseBespeak.getId())){
         	courseBespeak.setUpdateTime(nowTime);
         	if(StringUtils.isEmpty(courseBespeak.getRemark())){
         		courseBespeak.setRemark("修改预约");
         	}
         	//保存
         	courseDao.updateCourseBespeak(courseBespeak);
         	courseBespeak = courseDao.getCourseBespeakById(courseBespeak.getId());
         	//保存his
         	courseBespeak.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
     	}else{
     		if(bespeakSum>0){
         		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"已预约课程不能重复预约");
         	}
     		//预约人数加1,保存到课程表
         	course.setUpdateTime(nowTime);
         	course.setActualNum(course.getActualNum()+1);
         	courseDao.updateCourseInfo(course);
         	//生成课程预约的任务单号
         	String taskNumber =this.prouduceBespeakNo(courseBespeak.getCourseId());
         	courseBespeak.setTaskNumber(taskNumber);
         	courseBespeak.setId(SeqUtil.getSeqNo());//id
         	courseBespeak.setUpdateTime(nowTime);
         	courseBespeak.setCreateTime(nowTime);
         	if(StringUtils.isEmpty(courseBespeak.getRemark())){
         		courseBespeak.setRemark("预约");
         	}
         	//保存
         	courseDao.saveCourseBespeak(courseBespeak);
         	//保存his
         	courseBespeak.setUpdateType(Constants.HANDLE_TYPE_ADD);
     	}
     	courseBespeak.setUpdateExplain("新增课程预约");
     	courseDao.saveCourseBespeakHis(courseBespeak);
     	
     	rspMap.put("courseBespeakId", courseBespeak.getId());
 		return rspMap;
 	}
     
     /**
      * 生成课程预约的任务单号
      * 课程id+月份+日期+时分秒
      */
     public String prouduceBespeakNo(int courseId){
    	 //月份
    	 String minthStr = DateTimeUtil.getNowDateStr(DateTimeUtil.MM);
    	 //日
    	 String dayStr = DateTimeUtil.getNowDateStr(DateTimeUtil.dd);
    	 //时分秒
    	 String timeStr = DateTimeUtil.getNowDateStr(DateTimeUtil.HHmmss);
    	 //生成任务单号
    	 return courseId+minthStr+dayStr+timeStr;
     }
     /**
 	 * 通过预约id获取预约信息 
 	 */
     @Override
     public Map<String, Object> getCourseBespeakById(String courseBespeakId) throws Exception{
    	//创建线程安全的hashmap返回对象
   	  	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
   	  	rspMap.put("courseBespeak", courseDao.getCourseBespeakById(courseBespeakId));
   	  	return rspMap;
     }
     /**
      * 取消预约或签到
      */
      @Override
      public Map<String, Object> cancelBespeak(PtCourseBespeak courseBespeak) throws Exception {
    	  //创建线程安全的hashmap返回对象
    	  Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
    	  String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
    	  //状态
    	  int bespeakState = courseBespeak.getBespeakState();
    	  //通过id查询预约记录
    	  courseBespeak = courseDao.getCourseBespeakById(courseBespeak.getId());
    	  //判断是否为取消
    	  if(bespeakState==2){
    		  //通过课程id查询课程
           	  PtCourseInfo course = courseDao.getCourseInfoById(courseBespeak.getCourseId());
        	  //课程预约人数-1
           	  course.setUpdateTime(nowTime);
           	  course.setActualNum(course.getActualNum()+1);
           	  courseDao.updateCourseInfo(course);
           	  courseBespeak.setBespeakState(2);
           	  courseBespeak.setRemark("取消预约");
    	  }else{//签到
    		  courseBespeak.setBespeakState(3);
    		  courseBespeak.setRemark("签到");
    	  }
    	  //修改课程预约状态
       	  courseBespeak.setUpdateTime(nowTime);
       	  courseDao.updateCourseBespeak(courseBespeak);
    	  //保存操作记录
       	  courseBespeak.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
       	  courseBespeak.setUpdateExplain("取消课程预约");
       	  courseDao.saveCourseBespeakHis(courseBespeak);
    	  return rspMap;
      }
      
      /**
       * 分页查询预约
       */
       @Override
       public Map<String, Object> listCourseBespeakForPage(PtCourseBespeak courseBespeak) throws Exception {
     	  //创建线程安全的hashmap返回对象
     	  Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	  String nowTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
     	  //过期未签到的记录全部自动签到
     	  List<PtCourseBespeak> list = courseDao.listCourseBespeakOverdue();
     	  if(!CollectionUtils.isEmpty(list)){
     		  PtCourseBespeak updateCourseBespeakParam = new PtCourseBespeak(); 
     		  for (int i = 0; i < list.size(); i++) {
     			 updateCourseBespeakParam = list.get(i);
     			 updateCourseBespeakParam.setBespeakState(3);
     			 updateCourseBespeakParam.setUpdateTime(nowTime);
     			 updateCourseBespeakParam.setRemark("过期自动签到");
     			 courseDao.updateCourseBespeak(updateCourseBespeakParam);
     			 updateCourseBespeakParam.setUpdateExplain("过期自动签到");
     			 updateCourseBespeakParam.setUpdateType(Constants.HANDLE_TYPE_CHANGE);
     			 courseDao.saveCourseBespeakHis(updateCourseBespeakParam);
     		  }
     		  list.clear();
     	   }
     	  list = courseDao.listCourseBespeakForPage(courseBespeak);
     	  int totalCount = courseDao.countCourseBespeakForPage(courseBespeak);
		  rspMap.put("rows", list);
		  rspMap.put("totalCount", totalCount);
		  return rspMap;
      }
       /**
        * 查询有课程的近四天的日期
        */
       @Override
       public Map<String, Object> getCourseDayOfFour() throws Exception {
     	  //创建线程安全的hashmap返回对象
     	  Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	  
     	  List<String> dayList = courseDao.getCourseDayOfFour();
     	  
		  rspMap.put("dayList", dayList);
		  return rspMap;
      }
       /**
        * 条件查询预约数据（未分页，暂时供数据导出使用）
        */
       @Override
       public List<PtCourseBespeak> listCourseBespeak(PtCourseBespeak courseBespeak) throws Exception {
     	  List<PtCourseBespeak> list = courseDao.listCourseBespeak(courseBespeak);
     	  return list;
       }
       /**
        * 条件查询课程
        */
       @Override
       public List<PtCourseInfo> listCourseInfoForAll(PtCourseInfo courseInfo) throws Exception {
     	  List<PtCourseInfo> list = courseDao.listCourseInfoForAll(courseInfo);
     	  return list;
       }
       /**
        * 通过条件查询用户
        */
       @Override
       public Map<String, Object> selectPatientByParamForCourse(Map<String, Object> paramMap) throws Exception {
    	  Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
      	  List<Map<String, Object>> list = courseDao.selectPatientByParamForCourse(paramMap);
 		  rspMap.put("list", list);
 		  return rspMap;
       }
       
       /**
        * 跑数据使用
        */
       @Override
       public Map<String, Object> selectPDateForTime(Map<String, Object> paramMap) throws Exception {
     	  Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
     	  List<Map<String, Object>> list = courseDao.selectPatient(paramMap);
		  rspMap.put("list", list);
		  return rspMap;
      }
       /**
        * 查询用户可预约的近四天的所有课程
        */
       /**
        * 查询app用户课程预约首页接口实现
        * 1.查询近四天的课程
        * 2.查询当前年的所有课程
        */
        @Override
    	public Map<String, Object> getCourseForFourDayOfAll(PtCourseInfo courseInfo) throws Exception {
        	//创建线程安全的hashmap返回对象
        	Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
        	//获取最近四天的所有课程
        	List<PtCourseInfo> courseListFourDay = courseDao.getCourseForFourDayOfAll(courseInfo);
        	PtCourseBespeak courseBespeak = new PtCourseBespeak();
        	List<PtCourseInfo> fourDayList = new ArrayList<PtCourseInfo>();
        	//重新拼接四天的数据
        	if(!CollectionUtils.isEmpty(courseListFourDay)){
        		for (int i = 0; i < courseListFourDay.size(); i++) {
        			courseBespeak.setCourseId(courseListFourDay.get(i).getId());
        			courseBespeak.setBespeakState(1);//1：预约
        			courseBespeak.setUserId(courseInfo.getUserId());
        	     	//查询课程是否已经预约
        	     	int bespeakSum = courseDao.countCourseBespeak(courseBespeak);
        	     	if(bespeakSum<=0){
        	     		fourDayList.add(courseListFourDay.get(i));
        	     	}
				}
        		
        	}
        	rspMap.put("fourDayList", fourDayList);
    		return rspMap;
    	}
       
}
